package com.hyfrogx.modules.app.controller.attention;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hyfrogx.common.exception.ServiceException;
import com.hyfrogx.common.utils.QueryExt;
import com.hyfrogx.common.utils.R;
import com.hyfrogx.modules.app.annotation.Login;
import com.hyfrogx.modules.app.entity.HyUserAttentionEntity;
import com.hyfrogx.modules.app.entity.User;
import com.hyfrogx.modules.app.service.AttentionService;
import com.hyfrogx.modules.app.service.UserService;
import com.hyfrogx.modules.app.utils.FrogConstant;
import com.hyfrogx.modules.information.entity.HyInformationVerifyEntity;
import com.hyfrogx.modules.information.service.HyInformationVerifyService;
import com.hyfrogx.modules.manage.controller.BaseController;
import com.hyfrogx.modules.sys.service.SysUserRoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 我的关注
 *
 * @项目 hyplatform2.0
 * @日期: 2017年9月13日
 * @负责人: xjM
 */
@RestController
@RequestMapping(value = "api/attention")
@Api(value = "ApiAttentionController", tags = {"客户端--关注模块"})
public class ApiAttentionController extends BaseController {

  @Autowired
  private AttentionService attentionService;
  @Autowired
  private UserService userService;
  @Autowired
  private HyInformationVerifyService verifyService;
  @Autowired
  private SysUserRoleService sysUserRoleService;

  /**
   * 获取粉丝列表
   * <p>
   * 用户ID
   *
   * @return
   * @throws Exception
   */
  @GetMapping(value = "getPage")
  @Login
  @ApiOperation("获取粉丝列表")
  public R getpage(@RequestParam Map<String, Object> map) {
    try {
      Page page = attentionService.getMyFunsByUid(new QueryExt<>(map));
      List<HyUserAttentionEntity> result = page.getRecords();
      if(CollUtil.isNotEmpty(result)) {
        for (int i = 0; i < result.size(); i++) {
          Integer uid = result.get(i).getFid();
          // 获取每个被关注用户的角色
          User user = userService.getBaseMapper().selectOne(new QueryWrapper<User>().eq("uid", uid));
          if (user != null) {
            Integer roleId = sysUserRoleService.selectByAppUid(uid.intValue());
            result.get(i).setRid(roleId);
            if (roleId == FrogConstant.Role.MEDIA) {
              // 资讯号是否子公司资讯号
              HyInformationVerifyEntity vobject = verifyService.getVerifyRecordByUid(user.getUid().intValue());
              if (vobject != null) {
                result.get(i).setUsername(vobject.getUserName());
              }
            }

          }
        }
        return R.ok().put("data", page);
      }
      return R.ok().put("data", new Page<>());
    } catch (ServiceException e) {
      return R.error(e.getMessage());
    }
  }

  /**
   * ta的粉丝列表
   *
   * @return
   * @throws Exception
   */
  @GetMapping(value = "getpage/v2.0")
  @Login
  @ApiOperation("ta的粉丝列表")
  public R newGetpage(@ApiIgnore @RequestAttribute("userId") Long userId, @RequestParam Map<String, Object> map) throws Exception {
    if (ObjectUtil.isEmpty(map.get("sid"))) {
      return R.error("sid不能为空");
    }

    try {
      Page page = attentionService.getMyFunsByUid(new QueryExt<>(map));
      List<HyUserAttentionEntity> records = page.getRecords();
      for (int i = 0; i < page.getRecords().size(); i++) {
        Integer fuid = records.get(i).getFid();
        // 获取每个粉丝的角色
        User user = userService.getBaseMapper().selectOne(new QueryWrapper<User>().eq("uid", fuid));
        if (ObjectUtil.isNotNull(user)) {
          Integer roleId = sysUserRoleService.selectByAppUid(fuid);
          records.get(i).setRid(roleId);
          if (roleId == FrogConstant.Role.MEDIA) {
            // 资讯号是否子公司资讯号
            HyInformationVerifyEntity vobject = verifyService.getVerifyRecordByUid(user.getUid().intValue());
            if (vobject != null) {
              records.get(i).setUsername(vobject.getUserName());
            }
          }
        }
        // 每个粉丝对于当前登录用户的互相关注状态
        Integer status = attentionService.selectsta((int) fuid, userId.intValue());
        records.get(i).setSta(status);
      }
      return R.ok().put("data",page);
    } catch (ServiceException e) {
      return R.error(e.getMessage());
    }
  }

  /**
   * 粉丝列表修改粉丝状态
   *
   * @param userId 用户ID
   * @param fid    粉丝id
   * @return
   */
  @PostMapping(value = "edit")
  @Login
  @ApiOperation("粉丝列表修改粉丝状态")
  public R edit(@ApiIgnore @RequestAttribute("userId") Long userId,  Integer fid) {
    try {
      HyUserAttentionEntity hyUserAttention = new HyUserAttentionEntity();
      HyUserAttentionEntity flower = attentionService.getBaseMapper()
        .selectOne(new QueryWrapper<HyUserAttentionEntity>().eq("sid", userId).eq("fid", fid));

      Integer status = 1;
      if (flower == null) {
        hyUserAttention.setSid(userId.intValue());
        hyUserAttention.setFid(fid);
        hyUserAttention.setCreated(new Date());
        attentionService.getBaseMapper().insert(hyUserAttention);
        return R.ok().put("data", status);
      } else {
        attentionService.getBaseMapper()
          .delete(new QueryWrapper<HyUserAttentionEntity>().eq("sid", userId).eq("fid", fid));
        status = 0;
        return R.ok().put("data", status);
      }
    } catch (ServiceException e) {
      return R.error(e.getMessage());
    }
  }

  /**
   * 我的关注，我的关注主播列表
   *
   * @param
   * @return
   * @throws Exception
   */
  @GetMapping(value = "getSelfpage")
  @Login
  @ApiOperation("我的关注，我的关注主播列表")
  public R getSelfpage(@ApiIgnore @RequestAttribute("userId") Long userId,@RequestParam Map<String, Object> map) throws Exception {

    try {
      HyUserAttentionEntity funs = attentionService.getByFid(userId.intValue());
      if (funs == null) {
        return R.ok().put("data",new Page());
      } else {
        map.put("fid",userId);
        Page page = attentionService.getAllSunSid(new QueryExt(map));
        if(page.getRecords().size()>0) {
          List<HyUserAttentionEntity> result = page.getRecords();
          for (int i = 0; i < result.size(); i++) {
            // 获取每个被关注用户的角色
            User user = userService.getBaseMapper().selectOne(new QueryWrapper<User>().eq("uid", result.get(i).getSid()));
            if (user != null) {
              Integer roleId = sysUserRoleService.selectByAppUid(user.getUid().intValue());
              if (roleId == FrogConstant.Role.MEDIA) {
                // 资讯号是否子公司资讯号
                HyInformationVerifyEntity vobject = verifyService.getVerifyRecordByUid(user.getUid().intValue());
                if (vobject != null) {
                  result.get(i).setUsername(vobject.getUserName());
                }
              }

            }
          }
          return R.ok().put("data", page);
        }
        return R.ok().put("data",new Page());
      }
    } catch (ServiceException e) {
      return R.error(e.getMessage());
    }
  }

  /**
   * 我的关注修改关注状态
   * 关注用户，取关用户
   * @return
   */
  @PostMapping(value = "editSelf")
  @Login
  @ApiOperation("关注用户，取关用户")
  public R editSelf(@ApiIgnore @RequestAttribute("userId") Long userId,Integer sid) {
    if (sid == null || sid == 0) {
      return R.error("被关注者信息不合法");
    }
    try {
      HyUserAttentionEntity hyUserAttention = new HyUserAttentionEntity();
      HyUserAttentionEntity funs = attentionService.getBySidAndUid(sid, userId.intValue());
      Integer status = 0;
      if (funs == null) {
        hyUserAttention.setSid(sid);
        hyUserAttention.setFid(userId.intValue());
        hyUserAttention.setCreated(new Date());
        int result = attentionService.getBaseMapper().insert(hyUserAttention);
        status = 1;// 表示创建关注
        return R.ok().put("data",status);
      } else {
        attentionService.getBaseMapper()
          .delete(new QueryWrapper<HyUserAttentionEntity>().eq("sid", sid).eq("fid", userId));
        status = 0;
        return R.ok().put("data",status);
      }
    } catch (ServiceException e) {
      return R.error(e.getMessage());
    }
  }

  /**
   * 获取用户的粉丝数量
   *
   * @return
   */
  @GetMapping(value = "getfunsUnm")
  @Login
  @ApiOperation("获取用户的粉丝数量")
  public R getfunsUnm(@ApiIgnore @RequestAttribute("userId") Long userId) {
    try {
      Integer funsNum = 0;
      // 判断数据库内是否存在该用户信息，如果没有返回null，反之查询用户粉丝信息
      HyUserAttentionEntity attSuns = attentionService.getBaseMapper()
        .selectOne(new QueryWrapper<HyUserAttentionEntity>().eq("sid",userId));
      if (attSuns == null) {
        return R.ok().put("data",funsNum);
      } else {
        funsNum = attentionService.getBaseMapper()
          .selectCount(new QueryWrapper<HyUserAttentionEntity>().eq("sid",userId));
        return R.ok().put("data",funsNum);
      }
    } catch (ServiceException e) {
      return R.error(e.getMessage());
    }
  }

  /**
   * 获取用户的关注数量
   *
   * @return
   */
  @PostMapping(value = "getSunUnm")
  @Login
  @ApiOperation("获取用户的关注数量")
  public R getSunUnm(@ApiIgnore @RequestAttribute("userId") Long userId) {
    try {
      Integer sunNum = 0;
      HyUserAttentionEntity funs = attentionService.getByFid(userId.intValue());
      if (funs == null) {
        return R.ok().put("data",sunNum);
      } else {
        sunNum = attentionService.getBaseMapper()
          .selectCount(new QueryWrapper<HyUserAttentionEntity>().eq("fid",userId));
        return R.ok().put("data",sunNum);
      }
    } catch (ServiceException e) {
      return R.error(e.getMessage());
    }
  }

  /**
   * 获取与主播的关系状态
   *
   * @return
   */
  @GetMapping(value = "getType")
  @Login
  @ApiOperation("获取与主播的关系状态")
  public R getType(@ApiIgnore @RequestAttribute("userId") Long userId,Integer sid) {
    HyUserAttentionEntity hyUserAttention = new HyUserAttentionEntity();
    hyUserAttention.setSid(sid);
    hyUserAttention.setFid(userId.intValue());
    HyUserAttentionEntity fun = attentionService.getByFid(userId.intValue());
    Integer status = 0;// 0表示无关系，1表示存在关系
    if (fun == null) {
      return R.ok().put("data",status);
    } else {
      HyUserAttentionEntity funs = attentionService.getBaseMapper()
        .selectOne(new QueryWrapper<HyUserAttentionEntity>().eq("sid",sid).eq("fid",userId));
      if (funs == null) {

        return R.ok().put("data",status);
      } else {
        status = 1;
        return R.ok().put("data",status);
      }
    }
  }
}
